package cn.gpnu.web.servlet;

import cn.gpnu.dao.TreePriceDao;
import cn.gpnu.dao.Treedao;
import cn.gpnu.dao.Userdao;
import cn.gpnu.domain.Tree;
import cn.gpnu.domain.TreePrice;
import cn.gpnu.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //输出
        /*//获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //封装user对象
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);*/
        //2.获取所有请求参数
        Map<String, String[]> map = req.getParameterMap();
        //3.创建User对象
        User loginUser = new User();
        //3.2使用BeanUtils封装
        try {
            BeanUtils.populate(loginUser,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //4调用UserDao的login方法
        Userdao dao = new Userdao();
        User user = dao.login(loginUser);
        //判断User
        if(user == null) {
            //登陆失败
            req.getRequestDispatcher("/failServlet").forward(req,resp);
        }
        else {
            Treedao treedao = new Treedao();
            List<Tree> query = treedao.select_tree(user.getId());

            TreePriceDao treePriceDao = new TreePriceDao();
            List<TreePrice> treePrices = treePriceDao.select_price();


            HttpSession session = req.getSession(true);
            session.setMaxInactiveInterval(60*60*24);

            session.setAttribute("user",user);
            session.setAttribute("query",query);
            session.setAttribute("treePrices",treePrices);


            req.setAttribute("user",user);
            req.getRequestDispatcher("/JSP/time.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
